﻿Shader "Custom/TestShader5"
{
	Properties
	{
		_MainTex("MainTex", 2D) = "white" {}
		_BumpMap("Normal Map", 2D) = "bump" {}
		_RampTex("RampTex", 2D) = "white" {}
		_BumpScale("Bump Scale", float) = 1.0
		_Color("Color", color) = (1,1,1,1)
		_Diffuse("Diffuse", color) = (1,1,1,1)
		_Specular("Specular", color) = (1,1,1,1)
		_Gloss("Gloss", Range(8, 128)) = 20
	}

		SubShader
		{
			Pass
			{
				Tags{ "LightMode" = "ForwardBase" }

				CGPROGRAM
				#pragma vertex vert
				#pragma fragment frag
				#include "Lighting.cginc"	

				sampler2D _MainTex;
				float4 _MainTex_ST;
				sampler2D _BumpMap;
				float4 _BumpMap_ST;
				float _BumpScale;
				sampler2D _RampTex;
				fixed4 _Color;
				fixed4 _Diffuse;
				fixed4 _Specular;
				float _Gloss;
			  
				struct a2v
				{
					float4 vertex : POSITION;
					float3 normal : NORMAL;
					float4 texcoord : TEXCOORD0;
					float4 tangent : TANGENT;
				};

				struct v2f
				{
					float4 pos : SV_POSITION;
					float4 uv :TEXCOORD2;
					float3 lightDir :TEXCOORD0;
					float3 viewDir :TEXCOORD1;
				};

				v2f vert(a2v v)
				{
					v2f o;
					o.pos = UnityObjectToClipPos(v.vertex);
					o.uv.xy = v.texcoord.xy * _MainTex_ST.xy + _MainTex_ST.zw;
					o.uv.zw = v.texcoord.xy * _BumpMap_ST.xy + _BumpMap_ST.zw;

					float3 binormal = cross(normalize(v.normal), normalize(v.tangent.xyz)) * v.tangent.w;
					float3x3 rotation = float3x3(v.tangent.xyz, binormal, v.normal);

					o.lightDir = mul(rotation, ObjSpaceLightDir(v.vertex)).xyz;
					o.viewDir = mul(rotation, ObjSpaceViewDir(v.vertex).xyz);

					return o;
				}

				fixed4 frag(v2f i) : SV_Target
				{
					fixed3 tangentLightDir = normalize(i.lightDir);
					fixed3 tangentViewDir = normalize(i.viewDir);
					fixed4 packedNormal = tex2D(_BumpMap, i.uv.zw);
					fixed3 tangentNormal = UnpackNormal(packedNormal);
					tangentNormal.xy *= _BumpScale;
					tangentNormal.z = sqrt(1.0 - saturate(dot(tangentNormal.xy, tangentNormal.xy)));

					fixed3 albedo = tex2D(_MainTex, i.uv.xy).rgb * _Color.rgb;
					fixed3 ambient = albedo * UNITY_LIGHTMODEL_AMBIENT.xyz;
					fixed3 worldNormal = tangentNormal;
					fixed3 worldLight = tangentLightDir;

					fixed halfLambert = 0.5 * dot(worldNormal, worldLight) + 0.5;
					fixed3 rampColor = tex2D(_RampTex, fixed2(halfLambert, halfLambert)).rgb;

					fixed3 diffuse = rampColor * albedo * _Diffuse.rgb * _LightColor0.rgb * saturate(dot(worldNormal, worldLight));

					fixed3 reflectDir = normalize(reflect(-worldLight, worldNormal));
					fixed3 viewDir = tangentViewDir;

					fixed3 specular = _Specular.rgb * _LightColor0.rgb * pow(max(0,dot(reflectDir, viewDir)), _Gloss);

					return fixed4(diffuse + ambient + specular, 1);
				}

				ENDCG
			}
		}
	Fallback "Diffuse"
}